<?php
namespace App\Console\Commands;

use App\Models\FriendInvite;
use App\Models\FriendModel;
use App\Models\HxUsers;
use App\Models\Media;
use App\Models\MediaComment;
use App\Models\MediaLike;
use App\Models\MediaStar;
use App\Models\MessagesSentSucceed;
use App\Models\RandDigitalPool;
use App\Models\User;
use App\Models\UserDynamicList;
use App\Models\UserInvitationCode;
use App\Services\UserService;
use Illuminate\Support\Facades\DB;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Redis;
use App\Models\Shareholder;
use App\Models\MemberShip;
use App\Models\InviteSettlementCollect;
use App\Models\InviteRelationLog;

class sync extends Command {

    /**
     * @var 设置执行的命令
     */
    protected $signature  = 'sync:send {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    // protected $description = 'test controller';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 获取参数，调用方法
        $action = $this->argument('action');
        $this->$action();

        //这里做任务的具体处理，可以用模型
        // Log::info('任务调度'.time());
    }

    /*
     * 取消无效的亲友
     * 同步亲友圈
     * */
    public function sync_friend()
    {
        $list = FriendModel::where([['status', '=', '1']])->get();
        foreach ($list as $value){
            $userRows = User::where([['id', '=', $value->uid]])->first();
            // 过滤为空的无效用户
            if(empty($userRows)){
                $update = DB::update("update friend set status=0 where uid=".$value->uid." and friend_uid=".$value->friend_uid);
                $updatea = DB::update("update friend set status=0 where friend_uid=".$value->uid." and uid=".$value->friend_uid);
                continue;
            }

            // 同步添加
            $friend = FriendModel::where([['uid', '=', $value->friend_uid],['friend_uid', '=', $value->uid]])->first();
            if(empty($friend)){
                $friend = new FriendModel();
                $friend->uid = $value->friend_uid;
                $friend->friend_uid = $value->uid;
                $friend->status = 1;
                $friend->created_at = $value->created_at;
                $friend->updated_at = $value->updated_at;
                $friend->save();
            }else{
                if($friend->status == '0'){
                    $friend->status = 1;
                    $friend->save();
                }
            }
        }
        dd('end');
    }

    /*
     * 同步评论层级
     *
     * 要求：避免重复动态，删除所有动态，同步
     *
     * */
    public function sync_component()
    {

        $list = MediaComment::orderBy('parent_id','asc')->orderBy('id','asc')->get()->toArray();

        $redis_key = 'sync:media_comment';
        // 预存redis
        foreach ($list as $key=>$value){
            Redis::lpush($redis_key, json_encode($value));
        }

        $length = Redis::llen($redis_key);

        // 遍历
        for($i=0;$i<$length;$i++){
            $redis_data = json_decode(Redis::rpop($redis_key), true);
            // 同步动态
            $this->syncUserDynamicList($redis_key, $redis_data);

        }
        dd($length);
    }

    /*
     * 同步层级
     * */
    public function sync_comment_relation()
    {
        $list = MediaComment::select(['id','parent_id','relation_id','uid'])->orderBy('parent_id','asc')->orderBy('id','asc')->get()->toArray();
        $redis_key = 'sync:media_comment_relation';
        // 预存redis
        foreach ($list as $key=>$value){
            // 查询当前id 的单行
            $rows = MediaComment::where([['id', '=', $value['id']]])->first();
            $reply_uid = $value['uid'];
            $relation_id = ','.$value['id'].',';
            if(!empty($rows->relation_id))
                $relation_id = $rows->relation_id.$value['id'].",";

            $update = MediaComment::where([['parent_id', '=', $value['id']]])->update(['relation_id'=>$relation_id, 'reply_uid'=>$reply_uid]);
        }
        dd('end');
    }

    /*
     * 同步动态
     * */
    private function syncUserDynamicList($key, $redis_data)
    {
        $status = 1;
        // 识别是评论还是回复
        $type = ($redis_data['parent_id'] == '0' || empty($redis_data['parent_id'])) ? 1 : 2;
        // 评论未删
        if($redis_data['status'] != 1)
            $status = 0;

        // 评论的视频
        $media = \App\Models\Media::where([['id', '=', $redis_data['media_id']]])->first();
        if(empty($media)){
            Redis::lpush($key.":error_media_empty", json_encode($redis_data));
            return false;
        }

        // 未启用或已删除
        if($media->status != 1 || $media->is_delete == 1)
            $status = 0;

        // 回复
        if($type == 2){
            // 查找被回复的评论的用户id
            $reply_comment = MediaComment::where([['id', '=', $redis_data['parent_id']]])->first();
            $reply_comment_uid = 0;
            if(!empty($reply_comment)){
                $reply_comment_uid = $reply_comment->uid;
            }else{
                $status = 0;
            }
        }

        $UserDynamicListModel = UserDynamicList::where([['operation_id', '=', $redis_data['id']]])->first();
        if(empty($UserDynamicListModel)){
            $UserDynamicListModel = new UserDynamicList();
            $UserDynamicListModel->uid = ($type == 1) ? $media->uid : $reply_comment_uid;
            $UserDynamicListModel->type = $type;
            $UserDynamicListModel->operation_id = $redis_data['id'];//$comment->id;
            $UserDynamicListModel->parent_id = $redis_data['parent_id'];
            $UserDynamicListModel->option_uid = $redis_data['uid'];
            $UserDynamicListModel->media_id = $redis_data['media_id'];
            $UserDynamicListModel->option_other = $media->cover;
            $UserDynamicListModel->option_content = $redis_data['content'];
            $UserDynamicListModel->create_time = time();
            $UserDynamicListModel->update_time = time();
        }
        $UserDynamicListModel->status = $status;
        if(!$UserDynamicListModel->save())
            Redis::lpush($key.":error", json_encode($redis_data));
    }

    /*
     * 同步已发过短信
     * */
    public function sync_send_message()
    {

        $all = FriendInvite::select('mobile')->get();
        $scc_i = 0;
        $sc_i = 0;
        foreach ($all as $key=>$value){
            $temp_rows = MessagesSentSucceed::where([['mobile', '=', $value->mobile]])->first();
            if(!empty($temp_rows)){
                $sc_i++;
                continue;
            }
            $model = new MessagesSentSucceed();
            $model->msg_id = 0;
            $model->msg_type = 1;
            $model->mobile = str_replace('+86', '', $value->mobile);;
            $model->created_at = time();
            $model->remark = '脚本同步已发送邀请';
            $model->save();
            $scc_i++;
        }
        dd("已发：".$scc_i."--- 跳过：".$sc_i);
    }

    /*
     * 同步收藏列表
     * */
    public function sync_media_star()
    {
        $list = MediaStar::where([['status', '=', 1]])->get();
        foreach ($list as $key=>$value){
            MediaStar::set_media_star($value->uid, $value->media_id);
        }
        dd(count($list));
    }

    /*
     * 同步收藏列表
     * */
    public function sync_media_like()
    {
        $list = MediaLike::where([['is_delete', '=', '0']])->get();
        foreach ($list as $key=>$value){
            MediaLike::set_media_like($value->uid, $value->media_id);
        }
        dd(count($list));
    }

    /**
     * @desc 同步用户股东身份检测
     */
    public function sync_shareholders_user()
    {
        // 获取股东身份的用户，去股东表校验是否为股东
        $user_list = User::where(['role' => 1])->get(['id', 'mobile'])->toArray();
        $no_mobile = 0;
        $has_mobile = 0;
        if($user_list) {
            foreach($user_list as $user) {
                // 修改没有手机号码
                if(empty($user['mobile'])) {
                    User::where(['id' => $user['id']])->update(['role' => 0]);
                    $no_mobile ++;
                    continue;
                }
                $is_record = Shareholder::where(['mobile' => $user['mobile'], 'data_audit' => 1, 'fund_audit' => 1, 'status' => 0])->first();
                if(!$is_record) {
                    User::where(['mobile' => $user['mobile']])->update(['role' => 0]);
                    $has_mobile ++;
                }
            }
        }

        // 获取股东列表，去用户表校验是否存在股东身份
        $shareholder_number = 0;
        $shareholder_list = Shareholder::where(['data_audit' => 1, 'fund_audit' => 1, 'status' => 0])->get(['mobile'])->toArray();
        if($shareholder_list) {
            foreach($shareholder_list as $shareholder) {
                $is_record = User::where(['role' => 0, 'mobile' => $shareholder['mobile']])->first();
                if($is_record) {
                    $shareholder_number ++;
                    User::where(['mobile' => $shareholder['mobile']])->update(['role' => 1]);
                }
            }
        }

        dd("已处理没有手机号的股东用户：".$no_mobile."---有手机号的股东用户：".$has_mobile."----标识用户为股东身份的有".$shareholder_number);
    }
    /**
     * @return 用户邀请码同步
     */
    public function invitation_code_sync()
    {
        $allusercode = UserInvitationCode::select('uid')->get();
        foreach ($allusercode as $value){
            $key = "sync:code:".$value->uid;
            $expires_in = 3600;
            Redis::setex($key, $expires_in, $value->uid);
        }
        unset($key);

        $user_data = User::where('status', 1)->get(['id'])->toArray();
        foreach ($user_data as $user_id){
            $key = "sync:code:".$user_id['id'];
            if(Redis::get($key) == $user_id['id'])
                continue;

            $Generating_Invitation_Code = DB::table('rand_digital_pool')->where('status','=',0)->orderBy('id', 'ASC')->first(['number']);
            $checkInvitation_Code = UserInvitationCode::where('Invitation_code','=',$Generating_Invitation_Code->number)->first();
            $checkUser_id = UserInvitationCode::where('uid','=',$user_id['id'])->first();
            if(empty($checkInvitation_Code) && empty($checkUser_id)){
                $Invitation_Code_data =[
                    'uid'=>$user_id['id'],
                    'invitation_code' =>$Generating_Invitation_Code->number
                ];
                $insert_data =UserInvitationCode::insert($Invitation_Code_data);
                if($insert_data){
                    DB::table('rand_digital_pool')->where('number','=',$Generating_Invitation_Code->number)->update(['status'=>1]);
                }
            }
        }
        dd(count($user_data));
    }


    /*
     * 生成邀请码
     * */
    public function create_invite_code()
    {
        $key = 'rand_invite_code:';
        for ($i=1;$i<1000000;$i++){

            unset($number);
            $rand_code = $this->GetRandStr(6);
            if(!empty(Redis::get($key.':'.$rand_code)))
                continue;
            $number = ['number'=>$rand_code];
            $insert_arr[] = $number;
            Redis::setex($key.':'.$rand_code, 600, 1);

            if($i%100 == 0){
                $dd = RandDigitalPool::insert($insert_arr);
                unset($insert_arr);
            }
        }
    }

    /*
     * 生成随机所
     * */
    private function GetRandStr($length){
        $str='0123456789'; //abcdefghig
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /*
     * 同步注册环信
     * */
    public function reg_hx_user()
    {
        // 取出所有已生成环信用户的存到缓存
        $list = HxUsers::select(['id', 'uid'])->get();
        foreach ($list as $k=>$v)
            Redis::setex('sync:reg_hx_user'.':'.$v->uid, 3600, 1);
        unset($list);

        // 同步
        $all = User::select('id')->get();
        $i=0;
        foreach ($all as $key=>$value){
            $i++;
            if(!empty(Redis::get('sync:reg_hx_user'.':'.$value->id)))
                continue;

            $result = UserService::reg_hx_user($value->id);
            if(!$result)
                Redis::lpush('hx_user', $value->id);
        }
        dd('共同步注册环信用户：'.$i);
    }

    /**
     * @desc 同步所有用户到用户结算汇总表
     */
    public function sync_invite_settlement_user()
    {
        $user_data = User::where('status', 1)->get(['id','mobile','role','membership','parent_id', 'created_at'])->toArray();
        foreach($user_data as $user) {
            if($user['role'] == 1) {
                $ascription_info = Shareholder::where(['data_audit' => 1, 'fund_audit' => 1, 'status' => 0])->first(['ascription']);
            } elseif($user['membership'] == 1) {
                $ascription_info = MemberShip::where(['status' => 0])->first(['ascription']);
            }
            $settlement_collect_data = [
                'uid' => $user['id'],
                'created_at' => time(),
                'updated_at' => time(),
            ];
            $where_arr = ['uid' => $user['id']];

            if(isset($ascription_info) && !empty($ascription_info)) {
                $settlement_collect_data['ascription'] = $ascription_info->ascription;
            }

            if(!InviteSettlementCollect::where($where_arr)->first()) {
                InviteSettlementCollect::insert($settlement_collect_data);
            }

            if($user['parent_id'] > 0) {
                if(!InviteRelationLog::where(['invite_uid' => $user['parent_id'], 'reg_uid' => $user['id']])->first()) {
                    $invite_relation_data = [
                        'invite_uid' => $user['parent_id'],
                        'reg_uid' => $user['id'],
                        'reg_time' => strtotime($user['created_at'])
                    ];
                    InviteRelationLog::insert($invite_relation_data);
                }
            }
        }

        dd(1);
    }

    /*
     * 同步 视频浏览次数不能大于点赞数
     * */
    public function sync_media_pv()
    {
        $update_num = 0;
        $pagesize = 100;

        $total = Media::where([['is_delete', '=','0']])->count();
        $total_page = (int)ceil($total/$pagesize);
        for($i=1;$i<=$total_page;$i++) {
            $offset = ($i - 1) * $pagesize;
            $list = Media::select(['pv', 'like', 'id'])->where([['is_delete', '=', '0']])->skip($offset)->take($pagesize)->get()->toArray();

            if(!empty($list)){
                foreach ($list as $value){
                    if($value['like'] > $value['pv']){
                        $update_num++;
                        Media::where([['id', '=', $value['id']]])->update(['pv'=>$value['like']]);
                    }
                }
            }
        }
        dd($update_num);
    }

    public function sync_user_ascription()
    {
      $user_list =  User::where(['status'=>1])->get();
      $shareholder_list = Shareholder::where(['status'=>0])->get();
      $member_list = MemberShip::where(['status'=>0])->get();
      foreach ( $user_list as $user){
          foreach ($shareholder_list as $shareholder ){
             if($user->mobile == $shareholder->mobile){
                 $update_user = User::where(['status'=>1,'mobile'=>$shareholder->mobile])->update(['ascription' =>$shareholder->ascription]);
              }
          }
          if($user->ascription == 0){
              foreach ($member_list as $member ){
                  if($user->mobile == $member->mobile){
                    User::where(['status'=>1,'mobile'=>$member->mobile])->update(['ascription' =>$member->ascription]);
                  }
              }
          }

      }
      dd(count($update_user));
    }
}